<template>
  <div>
    <el-dialog :title="!dataForm.id ? '用户新增' : '用户编辑'" :close-on-click-modal="false" :visible.sync="visible" fullscreen center append-to-body>
      <el-button class="miui-dialog-close-btn" @click="visible = false">关闭页面</el-button>
      <el-card>
        <el-form :model="dataForm" :rules="dataRule" ref="dataForm" label-width="90px">
          <el-row>
            <el-col :span="8">
              <el-form-item label="用户名" prop="username" :rules="dataForm.id ? [{required: false}] : dataRule.username">
                <el-input v-model="dataForm.username" :disabled="dataForm.id ? true : false"  ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="姓名" prop="realName">
                <el-input v-model="dataForm.realName"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="密码" prop="password">
                <el-input v-model="dataForm.password" show-password></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="8">
              <el-form-item label="所属主部门" prop="deptId">
                <el-select v-model="dataForm.deptId" clearable>
                  <el-option v-for="item in deptOptions" :value="item.id" :label="item.name" :key="item.id"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="单位" prop="unitId">
                <el-select v-model="dataForm.unitId" clearable>
                  <el-option v-for="item in unitOptions" :value="item.id" :label="item.name" :key="item.id"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="岗位" prop="posId">
                <el-select v-model="dataForm.posId" clearable>
                  <el-option v-for="item in posOptions" :value="item.id" :label="item.name" :key="item.id"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
          <el-col :span="8">
            <el-form-item label="角色" prop="roles">
              <el-select v-model="dataForm.role" multiple placeholder="请选择" prop="roles" value-key="roleId">
                <el-option v-for="(item,index) in rolesOptions" :key="index.id" prop="roles" :label="item.roleName"
                           :value="item.roleId"></el-option>
              </el-select>
            </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="his系统工号" prop="hisWorkNumber">
                <el-input v-model="dataForm.hisWorkNumber"></el-input>
              </el-form-item>

              </el-col>
          </el-row>
          <el-row>
						<el-col :span="8">
						  <el-form-item label="岗位类型" prop="jobType">
						    <el-select multiple v-model="dataForm.jobType" placeholder="请选择" prop="jobType" value-key="jobType">
						      <el-option v-for="(item,index) in jobTypeOptions" :value="item.id" :label="item.jobName" :key="index.id"></el-option>
						    </el-select>
						  </el-form-item>
						</el-col>
          </el-row>
          <el-row>
            <el-col :span="8">
              <el-form-item label="手机号" prop="phone">
                <el-input v-model="dataForm.phone"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="状态" prop="lockFlag">
                <el-radio-group v-model="dataForm.lockFlag" size="small">
                  <el-radio label="0" border>有效</el-radio>
                  <el-radio label="9" border>锁定</el-radio>
                </el-radio-group>
                <!-- <el-input v-model="dataForm.lockFlag"></el-input> -->
              </el-form-item>
            </el-col>
            <el-col :span="8"></el-col>
          </el-row>
        </el-form>
      </el-card>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="dataFormSubmit()" v-prevent-re-click>保 存</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
    import {mapGetters} from 'vuex'
    import {getAddFeeObj, addAddFeeObj, putAddFeeObj} from '@/api/eims/add-fee'
    import { remote } from '@/api/admin/dict'
    import {getObj} from '@/api/admin/org'
    import {getInfoList} from '@/api/admin/jobtype'
    import { getTreeByUint, getDeptInfo, fetchTree } from '@/api/admin/dept'
    import { unitList } from '@/api/admin/unit'
    import { posQuery } from '@/api/admin/pos'
    import { getDetails, getUserObj, addUserObj,updateUserObj } from '@/api/admin/user'
    import { delUserObj, putUserObj, fetchList, updateUserOrg } from '@/api/admin/user'
    import { deptRoleList } from "@/api/admin/role";
    const that = this

    var validateUsername = (rule, value, callback) => {
      getDetails(value).then(response => {
        const result = response.data.data
        let userNamereg=/^\S+$/
        if (result !== null) {
          callback(new Error('用户名已经存在'))
        } else {
          if(!userNamereg.test(value)){
            callback(new Error('不允许有空格'))
          }else{
            callback()
          }
        }
      })
    };

    export default {
    data () {
      return {
        visible: false,
        supplyVisible: false,
        saveHandle: false,
        dataForm: {
          id: 0,
          username: '',
          realName: '',
          password: '',
          deptId: '',
          unitId: '',
          posId: '',
          lockFlag: '0',
        },
        jobTypeOptions: [],
        deptOptions: [],
        unitOptions: [],
        posOptions: [],
        rolesOptions:[],
        dataRule: {
          name: [{ required: true, message: '附加费用名称不能为空', trigger: 'blur' }],
          code: [{ required: true, message: '编码不能为空', trigger: 'blur' }],
          fee: [{ required: true, message: '附加金额不能为空', trigger: 'blur' }],

          username: [
            {required: true,message: '请输入用户名'},
            {min: 3,max: 10,message: '长度在 3 到 10 个字符',trigger: 'blur'},
            {validator: validateUsername, trigger: 'blur'},
          ],
          realName: [{required: true,message: '请输入姓名'}],
          password: [{min: 6,message: '长度在 6 到 20 个字符',trigger: 'blur'}],
          deptId: [{required: true,message: '请输入姓名'}],
          unitId: [{required: true,message: '请输入姓名'}],
        }
      }
    },
    components:{

    },
    computed: {
      ...mapGetters(['bizData'])
    },
    methods: {
      init(id,data,roleId) {
        this.visible = true
        for(let key in this.dataForm){
          this.dataForm[key] = ''
        }
        let role
        this.dataForm.id = id || 0
          console.log(this.dataForm)
          if(roleId) {
              role = roleId.split(',')
              for(let i = 0; i < role.length; i++){
                  role[i] = role[i]*1
              }

          }
        let orgData = Object.keys(data)

        if(orgData.length){
          if(data.extend == 'UNIT'){
            this.$set(this.dataForm,'unitId',data.relId)
          }else if(data.extend == 'DEPT'){
            this.$set(this.dataForm,'deptId',data.relId)
            getObj(data.parentId).then(response => {
                this.$set(this.dataForm,'unitId',response.data.data.relId)
            })
          }else if(data.extend == 'POS'){
            this.$set(this.dataForm,'posId',data.relId)
            this.$set(this.dataForm,'deptId',data.parentId)
              getObj(data.parentId).then(response1 => {
                  this.$set(this.dataForm,'deptId',response1.data.data.relId)
                  getObj(response1.data.data.parentId).then(response2 => {
                      this.$set(this.dataForm,'unitId',response2.data.data.relId)
                  })
              })
          }
        }
        this.getDeptOptions()
        this.getUnitOptions()
        this.getPosOptions()
        this.getJobTypeList()
        this.getRoleOptions()



        this.$nextTick(() => {
          // this.$refs['dataForm'].resetFields()
          if(this.dataForm.id){
            getUserObj(this.dataForm.id).then(result => {
              this.dataForm = result.data.data
                let jobTypeList = this.dataForm.jobType.split(',')
                let list = []
                jobTypeList.forEach(item => {
                    list.push(item*1)
                })
                this.$set(this.dataForm,'jobType',list)
              this.$set(this.dataForm,'role',role)
            })
          }
        })
      },
      //  获取部门列表
      getDeptOptions() {
        getDeptInfo().then(result => {
          this.deptOptions = result.data.data;
        })
      },
      //  获取单位列表
      getUnitOptions() {
        unitList().then(response => {
          this.unitOptions = response.data.data;
          console.log(this.unitOptions)
        })
      },
      // 获取岗位类型
      getJobTypeList(){
        getInfoList().then(result => {
          this.jobTypeOptions = result.data.data
        })
      },
      //  获取岗位列表
      getPosOptions() {
        let params = {current:1,size:1000}
        posQuery(params).then(response => {
          this.posOptions = response.data.data.records;
        })
      },
      //  获取角色列表
      getRoleOptions() {
          deptRoleList().then(response => {
              this.rolesOptions = response.data.data;
          });
      },
      // 表单提交
      dataFormSubmit () {
        this.dataForm.jobType= this.dataForm.jobType.toString();
        this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            if (this.dataForm.id) {
                updateUserObj(this.dataForm).then(data => {
                this.$message.success('修改成功')
                this.visible = false
                this.$emit('refreshDataList')
              });
            } else {
              addUserObj(this.dataForm).then(result => {
                this.$message.success('添加成功')
                this.visible = false
                this.$emit('refreshDataList')
              })
            }
          }
        })
      },
      // 打开选择供应商弹框
      openSupplyDialog () {
        this.supplyVisible = true
        this.$nextTick(() => {
          this.$refs.supplyDialog.init({ctgId: ''})
        })
      },
      getSupplyData(data) {
        this.dataForm.supplyId = data.id
        this.dataForm.supplyName = data.name
      },

    }
  }
</script>
